import router, { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

import { loginAPI, getUserInfoAPI, getUserPhotoAPI } from '@/api'
const getDefaultState = () => {
  return {
    token: getToken(), // 用户 Token，默认为 ''

    userInfo: {} // 用户信息对象

  }
}
const state = getDefaultState()

const mutations = {
  // 设置token
  SET_TOKEN(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 删除token
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  },
  // RESET_STATE: (state) => {
  //   Object.assign(state, getDefaultState())
  // },
  // 设置用户名
  SET_USER(state, value) {
    state.userInfo = value
  },
  // 删除头像
  REMOVE_USER(state) {
    state.userInfo = {}
  }
}

const actions = {
  async loginActions({ commit }, value) {
    const [err, res] = await loginAPI(value)
    if (!err) commit('SET_TOKEN', res.data)
    return [err, res]
  },
  // 获取-用户信息
  async getUserInfoActions({ commit }) {
    const res = await getUserInfoAPI() // 获取用户基本资料对象
    console.log(res)
    const res2 = await getUserPhotoAPI(res.data.userId)
    console.log(res2)
    commit('SET_USER', { ...res.data, ...res2.data }) // 保存到vuex的userInfo对象里
    return res.data.roles.menus
  },
  async logoutActions(store) {
    removeToken()
    store.commit('REMOVE_TOKEN')
    store.commit('RESET_STATE')
    // 路由对象也要从新生成
    resetRouter()
    router.replace(`/login?redirect=${router.currentRoute.fullPath}`)
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
